<template>
  <div class="app-container">
    <el-container class="layout-container">
      <el-aside width="auto" class="sidebar-container">
        <div class="logo-container">
          <img src="@/assets/logo.png" alt="Logo" class="logo" />
          <h1 v-if="!isCollapse">简易工具平台</h1>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          :collapse="isCollapse"
          :unique-opened="true"
          :collapse-transition="false"
          router
        >
          <el-menu-item index="/dashboard">
            <el-icon><Monitor /></el-icon>
            <template #title>仪表盘</template>
          </el-menu-item>

          <el-sub-menu index="/app-management">
            <template #title>
              <el-icon><Grid /></el-icon>
              <span>应用管理</span>
            </template>
            <el-menu-item index="/app-management/apps">应用列表</el-menu-item>
            <el-menu-item index="/app-management/categories">分类管理</el-menu-item>
            <el-menu-item v-if="isAdmin" index="/app-management/audits">审核管理</el-menu-item>
          </el-sub-menu>

          <el-sub-menu v-if="isAdmin" index="/user-management">
            <template #title>
              <el-icon><User /></el-icon>
              <span>用户管理</span>
            </template>
            <el-menu-item index="/user-management/users">用户列表</el-menu-item>
            <el-menu-item index="/user-management/roles">角色管理</el-menu-item>
          </el-sub-menu>
        </el-menu>
        <div class="sidebar-footer">
          <el-button
            type="text"
            class="collapse-btn"
            @click="toggleCollapse"
          >
            <el-icon v-if="isCollapse"><Right /></el-icon>
            <el-icon v-else><Left /></el-icon>
          </el-button>
        </div>
      </el-aside>

      <el-container class="main-container">
        <el-header class="header">
          <div class="header-left">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="item.path">
                {{ item.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <el-dropdown trigger="click">
              <div class="user-info">
                <el-avatar :src="userInfo.avatar" :size="32" />
                <span class="username">{{ userInfo.nickname || userInfo.username }}</span>
                <el-icon><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToUserProfile">个人中心</el-dropdown-item>
                  <el-dropdown-item @click="showChangePasswordDialog">修改密码</el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <el-main class="content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>

        <el-footer class="footer">
          <div class="copyright">
            &copy; {{ new Date().getFullYear() }} 简易工具管理平台 版权所有
          </div>
        </el-footer>
      </el-container>
    </el-container>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Monitor, Grid, User, Right, Left, ArrowDown } from '@element-plus/icons-vue';
import { changePassword as changePasswordApi } from '@/api/system/user.ts';
import { useUserStore } from '@/stores/user';
import type { FormInstance } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const isCollapse = ref(false);
const passwordDialogVisible = ref(false);
const passwordFormRef = ref<FormInstance>();

const userInfo = computed(() => userStore.userInfo);
const isAdmin = computed(() => userStore.hasRole('ADMIN'));

// 面包屑导航
const breadcrumbs = computed(() => {
  const result = [];
  const matched = route.matched;

  if (matched.length > 0) {
    result.push({
      path: '/',
      title: '首页'
    });

    matched.forEach(item => {
      if (item.meta && item.meta.title) {
        result.push({
          path: item.path,
          title: item.meta.title
        });
      }
    });
  }

  return result;
});

// 当前激活的菜单
const activeMenu = computed(() => {
  const { meta, path } = route;
  if (meta.activeMenu) {
    return meta.activeMenu;
  }
  return path;
});

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};

// 跳转到个人中心
const goToUserProfile = () => {
  router.push('/user-management/users/detail?id=' + userInfo.value.id);
};

// 显示修改密码对话框
const showChangePasswordDialog = () => {
  passwordForm.oldPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  passwordDialogVisible.value = true;
};

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return;

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await changePasswordApi({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
          confirmPassword: passwordForm.confirmPassword
        });
        ElMessage.success('密码修改成功，请重新登录');
        passwordDialogVisible.value = false;
        handleLogout();
      } catch (error: any) {
        ElMessage.error(error.message || '密码修改失败');
      }
    }
  });
};

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    userStore.logout();
    router.push('/login');
    ElMessage.success('已退出登录');
  } catch (error) {
    // 用户取消操作
  }
};
</script>

<style scoped>
.app-container {
  height: 100vh;
  width: 100vw;
}

.layout-container {
  height: 100%;
}

.sidebar-container {
  background-color: #304156;
  transition: width 0.3s;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  color: white;
  background-color: #263445;
}

.logo {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.logo-container h1 {
  font-size: 18px;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
}

.sidebar-menu {
  border-right: none;
  background-color: #304156;
  flex: 1;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: #bfcbd9;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  color: #409eff;
  background-color: #263445;
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background-color: #263445;
}

.sidebar-footer {
  padding: 16px;
  text-align: center;
  background-color: #263445;
}

.collapse-btn {
  color: #bfcbd9;
}

.main-container {
  height: 100%;
}

.header {
  background-color: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
  font-size: 14px;
}

.content {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}

.footer {
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 14px;
  border-top: 1px solid #e6e6e6;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
